import com.nokia.mid.sound.Sound;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.VolumeControl;

public class PlayMusic
        implements PlayerListener {

    public Player p;
    public InputStream is;
    public String path;
    public static final String AUDIO_FORMAT = "audio/mpeg";

    public PlayMusic(String path, int times, String geshi) {
        this.path = path;
        init(path, times, geshi);
    }

    public void init(String path, int times, String geshi) {
        try {
            System.out.println("------------------" + path);
            this.is = getClass().getResourceAsStream(path);
            if (this.p != null) {
                this.p.close();
                
            }
            this.p = Manager.createPlayer(this.is, geshi);
            this.p.realize();
            this.p.setLoopCount(times);

            VolumeControl volumeControl = (VolumeControl) this.p
                    .getControl("VolumeControl");
            volumeControl.setLevel(95);
            this.p.prefetch();
            this.p.addPlayerListener(this);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MediaException e) {
            e.printStackTrace();
        }
    }

    public void startSound() {
        try {
            this.p.start();
        } catch (Exception localException) {
        }
    }

    public void stopSound() {
        try {
            if (this.p.getState() == 400) {
            }
            this.p.stop();
            this.p.close();
            this.p.deallocate();
        } catch (MediaException localMediaException) {
        }
    }

    public void deallocate() {
        try {
            if (this.p.getState() == 400) {
            }
            this.p.stop();
            this.p.deallocate();
            this.p.close();
            this.p = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void playerUpdate(Player player, String event, Object eventData) {
        if (event.equals("endOfMedia")) {
            UIMain.vecMusic.removeElementAt(0);

            System.out.println("---------------------end"
                    + UIMain.vecMusic.size());
            if (UIMain.vecMusic.size() > 0) {
                UIMain.p.init((String) UIMain.vecMusic.elementAt(0), 1,
                        "audio/mpeg");
                UIMain.p.startSound();
            }
        }
    }
}
